package com.cgwx.controller;

import com.alibaba.fastjson.JSONObject;
import com.cgwx.Utils.result.ResultUtil;
import com.cgwx.aop.GetUserInfo;
import com.cgwx.common.utils.PageUtil;
import com.cgwx.config.BusinessException;
import com.cgwx.config.SuppressResponseLog;
import com.cgwx.data.dto.UserInfo;
import com.cgwx.entity.*;
import com.cgwx.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "个人空间")
@RequestMapping("/person")
public class PersonalController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IFolderService folderService;

    @Resource
    private ISharedService sharedService;

    @Resource
    private IFavoritesService favoritesService;

    @Resource
    private IRoomService roomService;

    @Resource
    private IPersonalRecycleBinService personalRecycleBinService;

    @GetMapping("/hello")
    @SuppressResponseLog
    @ApiOperation("测试打通")
    public Object hello() {
        return ResultUtil.success("hello");
    }

    @PostMapping("/uploadFile")
    @GetUserInfo
    @ApiOperation("上传文件")
    public Object uploadFile(UserInfo userInfo, @RequestParam String parentId, String type, @RequestParam MultipartFile multipartFile) {
        String account = userInfo.getUserId();
        String name = userInfo.getUserName();
        String deptId = userInfo.getDeptId();
        Folder folder = new Folder();
        folder.setEntityId(parentId);
        String roomId = folderService.getFolder(folder).get(0).getEntityRoom();
        String result = utilService.uploadFile(account, name, deptId, roomId, parentId, type, multipartFile, "false");
        return ResultUtil.success(result);
    }

    @PostMapping("/downloadFiles")
    @GetUserInfo
    @ApiOperation("下载文件")
    public Object downloadFiles(UserInfo userInfo, String type, String entityId) {
        String Url = utilService.getURLByFileId(userInfo.getUserId(), userInfo.getDeptId(), type, entityId);
        return ResultUtil.success(Url);
    }

    @GetMapping("/getPersonalTree")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取个人文件树")
    public Object getPersonalTree(UserInfo userInfo) {
        List<Folder> result = folderService.getPersonalTree(userInfo.getUserId());
        return ResultUtil.success(result);
    }

    @GetMapping("/OpenPersonal")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("打开个人文件夹")
    public Object OpenPersonal(UserInfo userInfo, @RequestParam String entityId, @RequestParam String openType, String keyword, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        List<FileFolder> fileFolders = folderService.OpenFolder(userInfo.getUserId(), userInfo.getDeptId(), entityId, keyword, openType, column, sort, "true");
        PageUtil<FileFolder> page = new PageUtil<FileFolder>().getPage(fileFolders.size(), pageSize, pageNum - 1);
        page.setList(page.startPage(fileFolders.size(), pageNum, pageSize, fileFolders));
        return ResultUtil.success(page);
    }

    @GetMapping("/insertPersonalFolder")
    @GetUserInfo
    @ApiOperation("新增个人文件夹")
    public Object insertPersonalFolder(UserInfo userInfo, @RequestParam String entityName, @RequestParam String parentId) {
        String account = userInfo.getUserId();
        String userName = userInfo.getUserName();
        String result = folderService.insertPersonalFolder(account, userName, entityName, parentId);
        List<Folder> folders = folderService.getPersonalTree(userInfo.getUserId());
        return ResultUtil.success(folders, result);
    }

    @GetMapping("/rename")
    @GetUserInfo
    @ApiOperation("文件(夹)重命名")
    public Object rename(UserInfo userInfo, @RequestParam String entityName, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.rename(userInfo.getUserId(), userInfo.getDeptId(), entityName, entityId, parentId, type);
        List<Folder> folders = folderService.getPersonalTree(userInfo.getUserId());
        return ResultUtil.success(folders, result);
    }

    @GetMapping("/deletePersonal")
    @GetUserInfo
    @Transactional
    @ApiOperation("根据entityId删除个人文件（夹）")
    public Object deletePersonal(UserInfo userInfo, String entityIds, String type) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = utilService.delete(userInfo.getUserId(), userInfo.getDeptId(), entityIdList, type);
        List<Folder> folders = folderService.getPersonalTree(userInfo.getUserId());
        return ResultUtil.success(folders, result);
    }

    @GetMapping("/getMyPersonalRecycleBin")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取个人空间的回收站")
    public Object getMyPersonalRecycleBin(UserInfo userInfo, String keyword, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        String roomId = roomService.getPersonalRoom(userInfo.getUserId());
        PageHelper.startPage(pageNum, pageSize);
        List<PersonalRecycleBin> result = personalRecycleBinService.getAllPersonalRecycleBin(userInfo.getUserId(), roomId, keyword, column, sort);
        return ResultUtil.success(new PageInfo<>(result));
    }

    @GetMapping("/getUsedSpace")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取已占用空间大小（单位是MB")
    public Object getUsedSpace(UserInfo userInfo, String type) {
        String result = roomService.getUsedSpace(userInfo.getUserId(), type);
        return ResultUtil.success(result);
    }

    @GetMapping("/restorePersonal")
    @GetUserInfo
    @Transactional
    @ApiOperation("根据entityId恢复个人文件（夹）")
    public Object restorePersonal(UserInfo userInfo, String entityIds, String type) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String account = userInfo.getUserId();
        String deptId = userInfo.getDeptId();
        String result = utilService.restore(account, deptId, entityIdList, type);
        List<Folder> folders = folderService.getPersonalTree(userInfo.getUserId());
        return ResultUtil.success(folders, result);
    }

    @GetMapping("/remove")
    @GetUserInfo
    @Transactional
    @ApiOperation("根据parentId移动个人文件（夹）")
    public Object remove(UserInfo userInfo, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.remove(userInfo.getUserId(), userInfo.getDeptId(), entityId, parentId, type);
        List<Folder> folders = folderService.getPersonalTree(userInfo.getUserId());
        return ResultUtil.success(folders, result);
    }

    @GetMapping("/removePersonalRecycleBin")
    @GetUserInfo
    @Transactional
    @ApiOperation("从回收站移动到个人空间")
    public Object removePersonalRecycleBin(UserInfo userInfo, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.removeRecycleBin(userInfo.getUserId(), userInfo.getDeptId(), entityId, parentId, type);
        List<Folder> folders = folderService.getPersonalTree(userInfo.getUserId());
        return ResultUtil.success(folders, result);
    }

    @GetMapping("/deletePersonalEntirely")
    @GetUserInfo
    @ApiOperation("彻底删除")
    public Object deletePersonalEntirely(UserInfo userInfo, @RequestParam String entityIds) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = personalRecycleBinService.deleteRecycleBinEntirelyById(entityIdList);
        List<Folder> folders = folderService.getPersonalTree(userInfo.getUserId());
        return ResultUtil.success(folders, result);
    }

    @GetMapping("/getMyShared")
    @GetUserInfo@SuppressResponseLog

    @ApiOperation("获取我的分享")
    public Object getMyShared(UserInfo userInfo, String keyword, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Shared> result = sharedService.getMyShared(userInfo.getUserId(), keyword, column, sort);
        return ResultUtil.success(new PageInfo<>(result));
    }

    @GetMapping("/getSharedMe")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取分享给我")
    public Object getSharedMe(UserInfo userInfo, String keyword, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Shared> shareds = sharedService.getSharedMe(userInfo.getUserId(), keyword, column, sort);
        List<Favorites> favorites = favoritesService.getFavorites(userInfo.getUserId(), userInfo.getDeptId(), null, column, sort);
        List<String> favoritesStr = new ArrayList<>();
        for(Favorites favorite : favorites) favoritesStr.add(favorite.getEntityId());
        for (Shared shared : shareds) {
            if (favoritesStr.contains(shared.getEntityId())) shared.setIsFavorite("true");
            else shared.setIsFavorite("false");
            if(shared.getIsCanceled().equals("true")) shared.setIsDeleted("true");
        }
        return ResultUtil.success(new PageInfo<>(shareds));
    }

    @GetMapping("/insertShared")
    @GetUserInfo
    @Transactional
    @ApiOperation("分享个人文件（夹）")
    public Object insertShared(UserInfo userInfo, String entityIds, String sharedIds) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        List<String> sharedIdList = JSONObject.parseArray(sharedIds, String.class);
        Shared shared = new Shared();
        shared.setAccount(userInfo.getUserId());
        String result;
        for(String sharedId: sharedIdList){
            shared.setSharedId(sharedId);
            for(String entityId: entityIdList){
                shared.setEntityId(entityId);
                //分享去重
                List<Shared> shareds = sharedService.getShared(shared);
                if(!shareds.isEmpty()){
                    Shared shared1 = shareds.get(0);
                    boolean flag = false;
                    if(shared1.getIsCanceled().equals("true")){
                        shared1.setIsCanceled("false");
                        flag = true;
                        if(sharedService.updateSharedById(shared1).equals("更新失败!")) throw new BusinessException("分享更新失败!");
                    }
                    if(shared1.getDeleteTime() != null){
                        shared1.setDeleteTime(null);
                        flag = true;
                        if(sharedService.updateSharedById(shared1).equals("更新失败!")) throw new BusinessException("分享更新失败!");
                    }
                    if(!flag) throw new BusinessException("已存在该分享!");
                    result = "分享成功!";
                }
                else result = sharedService.insertShared(shared);
                if(!result.equals("分享成功!")) throw new BusinessException("分享失败!");
            }
        }
        return ResultUtil.success("分享成功!");
    }

    @GetMapping("/deleteShared")
    @GetUserInfo
    @ApiOperation("被分享人根据分享id删除分享记录")
    public Object deleteShared(UserInfo userInfo, String ids) {
        List<String> idList = JSONObject.parseArray(ids, String.class);
        String result = sharedService.deleteSharedById(idList);
        return ResultUtil.success(result);
    }

    @GetMapping("/cancelShared")
    @GetUserInfo
    @ApiOperation("分享人根据分享id取消分享")
    public Object cancelShared(UserInfo userInfo, String ids) {
        List<String> idList = JSONObject.parseArray(ids, String.class);
        String result = sharedService.cancelSharedById(idList);
        return ResultUtil.success(result);
    }

    @GetMapping("/restoreShared")
    @GetUserInfo
    @ApiOperation("被分享人根据分享id恢复分享记录")
    public Object restoreShared(UserInfo userInfo, String ids) {
        List<String> idList = JSONObject.parseArray(ids, String.class);
        String result = sharedService.restoreSharedById(idList);
        return ResultUtil.success(result);
    }

    @GetMapping("/getFavorites")
    @GetUserInfo
    @SuppressResponseLog
    @ApiOperation("获取我的收藏")
    public Object getFavorites(UserInfo userInfo, String keyword, String column, String sort, @RequestParam int pageNum, @RequestParam int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Favorites> result = favoritesService.getFavorites(userInfo.getUserId(), userInfo.getDeptId(), keyword, column, sort);
        return ResultUtil.success(new PageInfo<>(result));
    }

    @GetMapping("/insertFavorites")
    @GetUserInfo
    @ApiOperation("收藏")
    public Object insertFavorites(UserInfo userInfo, String entityIds) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = favoritesService.insertFavorites(userInfo.getUserId(), entityIdList);
        return ResultUtil.success(result);
    }

    @GetMapping("/deleteFavorites")
    @GetUserInfo
    @ApiOperation("取消收藏")
    public Object deleteFavorites(UserInfo userInfo, String entityIds) {
        List<String> entityIdList = JSONObject.parseArray(entityIds, String.class);
        String result = favoritesService.deleteFavorites(userInfo.getUserId(), entityIdList);
        return ResultUtil.success(result);
    }
}